<template>
  <el-row>
    <el-card>
      <el-form ref="searchForm" :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item :label="$t('channel.tabData.createTime')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('channel.tabData.packageName')">
          <el-select v-model="searchForm.packageName" :placeholder="$t('channel.prompt.packageName')" style="width: 100%">
            <el-option
              v-for="item in allPackageData"
              :key="item.packageName"
              :label="item.packageName"
              :value="item.packageName"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('channel.tabData.channelId')">
          <el-input v-model="searchForm.id" :placeholder="$t('channel.prompt.channelId')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('channel.tabData.name')">
          <el-input v-model="searchForm.name" :placeholder="$t('channel.prompt.name')" :maxlength="50" />
        </el-form-item>
        <el-form-item :label="$t('channel.tabData.companyName')">
          <el-input v-model="searchForm.companyName" :placeholder="$t('channel.prompt.companyName')" :maxlength="50" />
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-button type="primary" @click="add">
        {{ $t('channel.btn.add') }}
      </el-button>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%;margin-top: 10px"
      >
        <el-table-column
          fixed="left"
          prop="id"
          :label="tableText['channelId']"
          min-width="80"
        />
        <el-table-column
          fixed="left"
          prop="name"
          :label="tableText['name']"
          min-width="100"
        />
        <el-table-column
          prop="packageName"
          :label="tableText['packageName']"
          min-width="250"
        />
        <el-table-column
          prop="companyName"
          :label="tableText['companyName']"
          min-width="100"
        />
        <el-table-column
          prop="link"
          :label="tableText['shareLink']"
          min-width="300"
        />
        <el-table-column
          prop="link"
          :label="tableText['QRCodeH5']"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="qrcode(scope.row.link)">
              {{ tableText['QRCodeDownload'] }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="apkUrl"
          :label="tableText['link']"
          min-width="300"
        />
        <el-table-column
          prop="apkUrl"
          :label="tableText['QRCodeApk']"
          min-width="120"
        >
          <template slot-scope="scope">
            <el-button type="text" @click="qrcode(scope.row.apkUrl)">
              {{ tableText['QRCodeDownload'] }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          prop="clearingWay"
          :label="tableText['method']"
          min-width="120"
        />
        <el-table-column
          :label="tableText['everyAmount']"
          min-width="120"
        >
          <template slot-scope="scope">
            {{ setAmount(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          fixed="right"
          prop="state"
          :label="tableText['channelStatus']"
          min-width="100"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['state']) }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="100"
        >
          <template slot-scope="scope">
            <el-button size="small" @click="editItem(scope.row)">
              {{ $t('common.operate.name') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <div id="qrCode" ref="qrcode" />
    <channel-h5-dialog
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      :package-data="allPackageData"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { getChannelH5 } from '@/api/operation'
import { allPackage } from '@/api/risk'
import { formatDate } from '@/utils/method'
import ChannelH5Dialog from '@/components/operation/channel-h5-dialog'
import QRCode from 'qrcodejs2'
export default {
  name: 'ChannelList',
  components: {
    ChannelH5Dialog
  },
  data() {
    return {
      loading: false,
      editDialog: false,
      tableData: [],
      allPackageData: [],
      tableText: {},
      totalNumber: 0,
      time: null,
      searchForm: this.params(),
      chooseItem: {
        id: null,
        name: null,
        clearingWay: null,
        packageName: null,
        companyName: null,
        everyAmount: null,
        everyAmountUnit: null,
        state: null,
        templateUrl: null
      }
    }
  },
  mounted() {
    this.tableText = this.$t('channel.tabData')
    this.getData()
    this.getAllPackage()
  },
  methods: {
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        id: null,
        name: null,
        createTimeStart: null,
        createTimeEnd: null,
        packageName: null,
        companyName: null,
        columns: ['state'],
        orderBy: [true]
      }
    },
    getAllPackage() {
      allPackage()
        .then(res => {
          if (res.success) {
            this.allPackageData = res.data.filter(v => {
              return v.packageName !== null
            })
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    reset() {
      this.searchForm = this.params()
      this.getData()
    },
    getData() {
      this.loading = true
      const data = this.searchForm
      if (this.time && this.time.length > 1) {
        data['createTimeStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['createTimeEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      } else {
        data['createTimeStart'] = null
        data['createTimeEnd'] = null
      }
      getChannelH5(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error(err.message)
        })
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    setValue(val) {
      const name = this.$t('channel.channelStatus').filter(item => {
        return item.value === val
      })
      return (name && name[0] && name[0].desc) ? name[0].desc : ''
    },
    setAmount(item) {
      const unit = this.$t('channel.unit').filter(v => {
        return v['value'] === item['everyAmountUnit']
      })
      const everyAmountUnit = unit && unit[0] && unit[0]['desc'] ? unit[0]['desc'] : ''
      return item['everyAmount'] ? item['everyAmount'] + everyAmountUnit : ''
    },
    add() {
      this.choose({})
      this.editDialog = true
    },
    editItem(item) {
      this.choose(item)
      this.editDialog = true
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    editSuccess() {
      this.getData()
    },
    choose(param) {
      this.chooseItem.id = param.id
      this.chooseItem.name = param.name
      this.chooseItem.link = param.link
      this.chooseItem.clearingWay = param.clearingWay
      this.chooseItem.packageName = param.packageName
      this.chooseItem.companyName = param.companyName
      this.chooseItem.everyAmount = param.everyAmount
      this.chooseItem.everyAmountUnit = param.everyAmountUnit
      this.chooseItem.state = param.state
      this.chooseItem.templateUrl = param.templateUrl
    },
    qrcode(data) {
      new QRCode('qrCode', {
        width: 200, // 设置宽度，单位像素
        height: 200, // 设置高度，单位像素
        text: data // 设置二维码内容或跳转地址
      })
      const canvasElement = document.getElementById('qrCode').firstChild
      const MIME_TYPE = 'image/png'
      const imgURL = canvasElement.toDataURL(MIME_TYPE)
      const dlLink = document.createElement('a')
      dlLink.download = data
      dlLink.href = imgURL
      dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':')
      document.body.appendChild(dlLink)
      dlLink.click()
      document.body.removeChild(dlLink)
    }
  }
}
</script>

<style lang="scss" scoped>
  .el-card{
    margin: 10px;
  }
  #qrCode{
    display: none;
  }
</style>
